package com.gateway.admin.gay;

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.gateway.common.constants.Constants;
import com.gateway.config.gay.nacos.NacosServiceConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Huangkai
 */
@Slf4j
@Component
public class GayPublish {

    @Value("${spring.gray.gateway.enabled}")
    private String enabled;

    @Autowired
    NacosServiceConfig nacosServiceConfig;

    /**
     * 执行灰度发布
     */
    public void gayPublish(String serviceName, ServerHttpRequest serverHttpRequest){
        operationGay(serviceName, serverHttpRequest);
    }

    public void operationGay(String serviceName, ServerHttpRequest serverHttpRequest){
        //对相关服务信息进行灰度
        List<Instance> instanceList =  nacosServiceConfig.configService(serviceName);
        List<Instance> gayInstanceList = instanceList.stream().filter(instance -> instance.getMetadata().containsKey("isGay")).collect(Collectors.toList());
        //网关是否需要进行灰度判断
        if(enabled.equals(Constants.STR_ONE)){
            //如果服务中配置了灰度，则进行灰度
            if(!CollectionUtils.isEmpty(gayInstanceList)){
                if(serverHttpRequest.getHeaders().containsKey("isGay")){
                    String isGay = serverHttpRequest.getHeaders().get("isGay").stream().filter(e -> e != null).findFirst().orElse("false");
                    log.info("该请求为灰度{}", isGay);
                }
            }
        }
    }
}
